<template>
  <div class="app-container search-list">
    <!-- PC端表格视图 -->
    <div v-if="!isMobile">
      <table-pagination
          ref="el-search-table"
          :fetch="getData"
          type="remote"
          :adaptive="fixOption"
          :page-sizes="[20, 50, 100]"
          :columns="columns"
          :form-options="formOptions"
          list-field="records"
          total-field="totalElements"
          page-index-key="page"
          page-size-key="pageSize"
          height="300"
          method="get"
          @selection-change="handleSelectionChange">
        <template slot="button">
          <div>
            <el-button type="primary" size="mini" @click="batchRecall()">批量召回</el-button>
            <el-button type="primary" size="mini" @click="settingVisible = true">导出订单</el-button>
          </div>
        </template>
        <el-table-column label="订单号" slot="append" width="180px" fixed='left' align='left'>
          <template slot-scope="{row}">
            <a style="color: #1A89FF" @click="handleDetail(row.id)">{{ row.orderNumber }}</a>
          </template>
        </el-table-column>
        <el-table-column label="操作" slot="append" fixed="right" width="100px">
          <template slot-scope="scope">
            <el-button v-if="scope.row.recallStatus===3" plain size="mini" type="primary"
                      @click="handleReCall(scope.row.id)">召回
            </el-button>
          </template>
        </el-table-column>
      </table-pagination>
    </div>

    <!-- 移动端列表视图 -->
    <mobile-order-recall-list v-else :siteId="siteId" />

    <el-dialog title="发送邮件" :visible.sync="recallDialogVisible" width="800px" center>
      <el-form label-width="120px">
        <el-form-item label="选择优惠码">
          <el-select v-model="code" placeholder="优惠码" clearable>
            <el-option v-for="item in couponCodeList" :value="item.couponCodeId" :label="item.activityName"
                      :key="item.activityName"></el-option>
          </el-select>
          <router-link :to="{name: 'coupon-codes-add'}" style="margin-left: 15px;  white-space: nowrap;color: #1f7df8;">
            新建优惠码
          </router-link>
        </el-form-item>
        <el-form-item label="邮件模板">
          <el-select v-model="marketingParentId" placeholder="邮件模板" @change="initEmailModelsList(marketingParentId)">
            <el-option v-for="item in marketingParentList" :value="item.id" :label="item.noticeName"
                      :key="item.id"></el-option>
          </el-select>
          <el-select v-model="marketingId" placeholder="邮件模板">
            <el-option v-for="item in marketingList" :value="item.id" :label="item.emailModelName"
                      :key="item.id"></el-option>
          </el-select>
          <span style="margin-left: 15px;  white-space: nowrap;color: #1f7df8;" @click="goGoodsDetail('inform-template-list', 3, marketingParentId, 'marketing_activity')">
            模板管理
          </span>
          <span style="margin-left: 15px;  white-space: nowrap;color: #1f7df8;" @click="goGoodsDetail('inform-template-add', 3, marketingParentId, 'marketing_activity')">
            新增邮件模板
          </span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="handlePrew(marketingId)">预览</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
         <el-button @click="recallDialogVisible = false;code=null">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="postRecall">确 定</el-button>
    </span>
    </el-dialog>
    <el-dialog title="优惠码" :visible.sync="batchRecallDialogVisible" width="800px" center>
      <el-form label-width="120px">
        <el-form-item label="选择优惠码">
          <el-select v-model="code" placeholder="优惠码" clearable>
            <el-option v-for="item in couponCodeList" :value="item.couponCodeId" :label="item.activityName"
                      :key="item.activityName"></el-option>
          </el-select>
          <router-link :to="{name: 'coupon-codes-add'}" style="margin-left: 15px;  white-space: nowrap;color: #1f7df8;">
            新建优惠码
          </router-link>
        </el-form-item>
        <el-form-item label="邮件模板">
          <el-select v-model="marketingParentId" placeholder="邮件模板" @change="initEmailModelsList(marketingParentId)">
            <el-option v-for="item in marketingParentList" :value="item.id" :label="item.noticeName"
                      :key="item.id"></el-option>
          </el-select>
          <el-select v-model="marketingId" placeholder="邮件模板">
            <el-option v-for="item in marketingList" :value="item.id" :label="item.emailModelName"
                      :key="item.id"></el-option>
          </el-select>
          <span style="margin-left: 15px;  white-space: nowrap;color: #1f7df8;" @click="goGoodsDetail('inform-template-list', 3, marketingParentId, 'marketing_activity')">
            模板管理
          </span>
          <span style="margin-left: 15px;  white-space: nowrap;color: #1f7df8;" @click="goGoodsDetail('inform-template-add', 3, marketingParentId, 'marketing_activity')">
            新增邮件模板
          </span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="handlePrew(marketingId)">预览</el-button>
        </el-form-item>
      </el-form>
        <span slot="footer" class="dialog-footer">
         <el-button @click="batchRecallDialogVisible = false;code=null">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="postBatchRecall">确 定</el-button>
    </span>
    </el-dialog>
    <el-dialog :visible.sync="isOpen" title="" :append-to-body="true"  class="custom-url" @close="isOpen=false">
      <iframe :srcdoc="showTemplateContent" frameborder="0" width="100%" height="600px"></iframe>
    </el-dialog>
    <el-dialog :visible.sync="settingVisible" title="订单导出" width="400px">
      <div class="desc">
        <div class="export" style="text-align: left;">
          <header>导出范围</header>
          <section>
            <div class="orca-row orca-form-item">
              <el-radio v-model="exportType" label="all" style="margin-bottom: 15px">所有订单</el-radio>
              <el-radio v-model="exportType" label="filter">符合当前筛选条件的订单</el-radio>
            </div>
          </section>
        </div>
        <div style="margin-top: 20px">
          <el-button type="primary" @click="handleExport" :loading="submitLoading">
            {{ submitLoading ? '导出中' : '导出' }}
          </el-button>
          <el-button @click="settingVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TablePagination from '_c/Tables/table-pagination';
import MobileOrderRecallList from '@/components/MobileOrderRecallList';
import {getOrderRecallPage, orderRecall} from '@/api/order';
import {currency, utcFormat} from '@/utils/filters';
import {mapGetters} from 'vuex';
import {getCouponCodeList} from '@/api/marketing';
import {getEmailModelsList, getMarketingList} from '@/api/inform';
import {getToken} from '@/utils/auth';
import axios from 'axios';

export default {
    name: 'order-recall-list',
    components: {
        TablePagination,
        MobileOrderRecallList
    },
    data () {
        return {
            settingVisible: false,
            headers: {'X-TULIANG-Session-Token': getToken()},
            exportType: 'all',
            marketingParentId: '',
            marketingId: '',
            submitLoading: false,
            couponCodeList: [],
            recallDialogVisible: false,
            batchRecallDialogVisible: false,
            code: null,
            batchCode: null,
            fixOption: {fixedHeader: true},
            selectedIdList: [],
            recallId: '',
            templateList: [],
            marketingParentList: [],
            marketingList: [],
            pageParams: {
                page: 1,
                pageSize: 20,
                recallStatus: '',
                orderNumber: '',
                email: '',
                startTime: '',
                endTime: ''
            },
            formOptions: {
                showResetBtn: true,
                showSearchBtn: true,
                inline: false,
                labelWidth: 120,
                submitBtnText: '查询',
                size: 'small',
                resetBtnCallback: () => {
                    this.pageParams = {
                        ...this.pageParams,
                        ...{
                            page: 1,
                            pageSize: 20,
                            recallStatus: '',
                            orderNumber: '',
                            email: '',
                            startTime: '',
                            endTime: ''
                        }
                    };
                    this.$refs['el-search-table'].resetFields();
                    this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                },
                forms: [
                    {prop: 'orderNumber', label: '订单号：', placeholder: '请输入订单号'},
                    {prop: 'email', label: '邮箱：', placeholder: '请输入邮箱'},
                    {
                        prop: 'recallStatus',
                        label: '召回状态：',
                        itemType: 'select',
                        placeholder: ' 请选择召回状态',
                        options: [
                            {value: '', label: '所有状态'},
                            {value: '1', label: '召回中'},
                            {value: '2', label: '召回成功'},
                            {value: '3', label: '召回失败'}
                        ]
                    },
                    {
                        prop: ['startTime', 'endTime'],
                        label: '下单时间：',
                        itemType: 'daterange',
                        startPlaceholder: ' 开始日期',
                        endPlaceholder: ' 结束日期'
                    }
                ]
            },
            columns: [
                {label: '', type: 'selection'},
                {label: '下单邮箱', prop: 'email', showOverflowTooltip: true},
                {
                    label: '订单金额',
                    prop: 'payAmount',
                    render: row => {
                        if (row.payAmount) {
                            return currency(row.payAmount, row.currencySymbol || '$');
                        }
                        return '';
                    }
                },
                {
                    label: '下单时间',
                    prop: 'createDate',
                    render: row => {
                        return utcFormat(row.createDate, 'YYYY-MM-DD HH:mm:ss', this.timeZone);
                    },
                    width: '180px'
                },
                {label: '商品数', prop: 'totalItemNum'},
                {label: '国家/地区', prop: 'country', showOverflowTooltip: true},
                {label: '召回状态', prop: 'recallStatusText'},
                {label: '召回次数', prop: 'recallNum'}
            ],
            showTemplateContent: '',
            isOpen: false
        };
    },
    created () {
        this.initCouponCode();
    },
    methods: {
        getData (params) {
            this.pageParams.siteId = this.siteId;
            params.startTime = this.getSiteTimeZoneStartTime(params.startTime);
            params.endTime = this.getSiteTimeZoneEndTime(params.endTime);
            this.pageParams = {...this.pageParams, ...params};
            return new Promise((resolve, reject) => {
                getOrderRecallPage(this.pageParams).then((res) => {
                    resolve(res);
                });
            });
        },
        handleSelectionChange (records) {
            if (records && records.length > 0) {
                this.selectedIdList = records;
            } else {
                this.selectedIdList = [];
            }
        },
        handlePrew (id) {
            this.isOpen = true;
            this.showTemplateContent = '';
            setTimeout(() => {
                this.showTemplateContent = this.marketingList.find(s => s.id === id).emailModelSourceCode;
            });
        },
        // 订单召回
        handleReCall (id) {
            this.recallDialogVisible = true;
            this.initMarketingList();
            this.recallId = id;
        },
        // 批量召回
        batchRecall () {
            if (!this.selectedIdList.length) {
                return this.$message.warning('请先选择需要召回的订单！');
            }
            if (this.selectedIdList.every(s => s.recallStatus !== 3)) {
                return this.$message.warning('没有选中可以发送召回邮件订单');
            }
            this.batchRecallDialogVisible = true;
            this.initMarketingList();
        },
        postRecall () {
            orderRecall({
                orderIds: this.recallId.toString(),
                siteId: this.siteId,
                couponCodeId: this.code,
                emailModelId: this.marketingId
            }).then(res => {
                if (res.code === '200') {
                    this.$message.success('发送成功');
                    this.code = null;
                    this.recallDialogVisible = false;
                    this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                }
            }).catch(() => {
                this.recallDialogVisible = false;
                this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
            });
        },
        postBatchRecall () {
            orderRecall({
                orderIds: this.selectedIdList.map(s => s.id).join(','),
                siteId: this.siteId,
                couponCodeId: this.code,
                emailModelId: this.marketingId
            }).then(res => {
                if (res.code === '200') {
                    this.$message.success('发送成功');
                    this.code = null;
                    this.batchRecallDialogVisible = false;
                    this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                }
            }).catch(() => {
                this.batchRecallDialogVisible = false;
                this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
            });
        },
        initCouponCode () {
            getCouponCodeList({
                siteId: this.siteId
            }).then(res => {
                this.couponCodeList = res.data;
            });
        },
        initMarketingList () {
            getMarketingList({siteId: this.siteId}).then(res => {
                this.marketingParentList = res.data;
                this.marketingParentId = this.marketingParentList.find(s => s.noticeDetailType === '0').id;
                this.initEmailModelsList(this.marketingParentId);
            });
        },
        initEmailModelsList (id) {
            getEmailModelsList({siteId: this.siteId, noticeId: id, emailType: 3}).then(res => {
                this.marketingList = res.data;
                const codeId = this.marketingParentList.find(s => s.id === id).promotionCodeId || '';
                const codeInId = this.couponCodeList.find(s => s.couponCodeId === codeId);
                this.code = (codeInId && codeInId.couponCodeId) || '';
                this.marketingId = this.marketingList.find(s => s.emailDefaultState === '0').id;
            });
        },
        handleDetail (id) {
            this.$router.push({name: 'order-detail', params: {id}, query: {type: 'recall'}});
        },
        getSiteTimeZoneStartTime (startTime) {
            if (startTime === undefined || startTime == null || startTime === '') {
                return startTime;
            }
            let tempTime = new Date(startTime);
            let month = (tempTime.getMonth() + 1 + 100).toString().substr(1);
            let date = (tempTime.getDate() + 100).toString().substr(1);
            let timeZoneStr = [tempTime.getFullYear(), month, date].join('/') + ' 00:00:00 UTC' + this.timeZone;
            return new Date(timeZoneStr).getTime();
        },
        getSiteTimeZoneEndTime (endTime) {
            if (endTime === undefined || endTime == null || endTime === '') {
                return endTime;
            }
            let tempTime = new Date(endTime);
            let month = (tempTime.getMonth() + 1 + 100).toString().substr(1);
            let date = (tempTime.getDate() + 100).toString().substr(1);
            let timeZoneStr = [tempTime.getFullYear(), month, date].join('/') + ' 23:59:59 UTC' + this.timeZone;
            return new Date(timeZoneStr).getTime();
        },
        goGoodsDetail (name = 'inform-template-list', emailType, noticeId, tag) {
            let routeData = this.$router.resolve({
                name,
                query: {...this.$route.query, emailType, noticeId, tag}
            });
            window.open(routeData.href, '_blank');
        },
        downloadURL (data) {
            const blob = new Blob([data], {type: 'application/vnd.ms-excel'});
            console.log(blob);
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = '召回订单列表' + '_' + this.siteId + '_' + new Date().getTime().toString() + (Math.random().toFixed(2) * 400 + 100).toString() + '.xlsx';
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            URL.revokeObjectURL(link.href);
            document.body.removeChild(link);
        },
        handleExport () {
            this.submitLoading = true;
            let params = {siteId: this.siteId, type: 1};
            params = this.exportType === 'all' ? params : Object.assign(params, this.pageParams);
            axios({
                method: 'get',
                params,
                url: this.exportPath,
                headers: {
                    'X-TULIANG-Session-Token': getToken()
                },
                responseType: 'arraybuffer'
            }).then(res => {
                this.downloadURL(res.data);
                this.submitLoading = false;
            });
        }
    },
    computed: {
        ...mapGetters([
            'timeZone',
            'siteList',
            'isMobile' // 从 Vuex store 获取移动设备状态
        ]),
        siteId () {
            return this.$store.state.user.siteId;
        },
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        },
        exportPath () {
            return `${process.env.VUE_APP_BASE_API}/order/export`;
        }
    }
};
</script>

<style scoped lang="scss">
.search-list {
  h4 {
    border-bottom: 1px solid #E8E8E8;
    margin: 0;
    margin-bottom: 10px;
    padding-bottom: 10px;
  }
}

.recall {
  display: flex;
  align-items: center;

  .text {
    margin-right: 20px;
  }
}

/* 移动端样式 */
@media screen and (max-width: 768px) {
  .app-container {
    padding: 10px !important;
  }

  .el-dialog {
    width: 90% !important;
    margin-top: 20vh !important;
  }
}
</style>
